﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Net;
using System.Collections;


namespace CanalDeNoticiasMSDNv2.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        public const string _spain = "http://channel9.msdn.com/Blogs/channel9spain/RSS";
        public const string _noticiasLink = "http://www.microsoft.com/spain/msdn/rss/noticias.xml";
        public const string _articulosLink = "http://www.microsoft.com/spain/msdn/rss/articulos.xml";


        public MainViewModel()
        {
            Videos = new ObservableCollection<ElementoEntradaVideo>();
            Noticias = new ObservableCollection<ElementoEntradaRss>();
            Articulos = new ObservableCollection<ElementoEntradaRss>();
        }


        public ObservableCollection<ElementoEntradaVideo> Videos
        {
            get;
            private set;
        }

        public ObservableCollection<ElementoEntradaRss> Noticias
        {
            get;
            private set;
        }

        public ObservableCollection<ElementoEntradaRss> Articulos
        {
            get;
            private set;
        }

        public void LoadData()
        {
            fillVideos(_spain);
            fillRss(_articulosLink, Articulos);
            fillRss(_noticiasLink, Noticias);
        }

        private void fillVideos(string rssUrl)
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (x, e) =>
            {
                if (e.Error == null)
                {
                    List<ElementoEntradaVideo> elements = ElementoEntradaVideo.GetElements(e.Result);
                    elements.ForEach((element) => this.Videos.Add(element));
                }
            };
            client.DownloadStringAsync(
                new Uri(rssUrl));
        }

        private void fillRss(string rssUrl, ObservableCollection<ElementoEntradaRss> collection)
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (x, e) =>
            {
                if (e.Error == null)
                {
                    List<ElementoEntradaRss> elements = ElementoEntradaRss.GetElements(e.Result);
                    elements.ForEach((element) => collection.Add(element));
                }
            };
            client.DownloadStringAsync(
                new Uri(rssUrl));
        }
    }
}